﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class SalesOrderPaymentManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack)
            {
                if (Request.QueryString["SalesOrderID"] != null)
                {
                    if (Request.QueryString["SalesOrderID"].ToString() != null)
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblSalesOrderID.Text = Request.QueryString["SalesOrderID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据


                //给日期输入框添加只读属性，不能在属性里直接设置，不然会取不到值
                this.txtDateReckoning.Attributes["readonly"] = "true";
                this.txtDateReckoning.Date = System.DateTime.Now;
                //设置经办人
                Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                this.lblManagerTrueName.Text = currentUser.TrueName;
                this.lblManagerUserName.Text = currentUser.UserName;
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(h => h.ClassID == (int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                this.BindAccountID();
                this.ShowCurrentBalance();
                this.lblInfoTo.Text = "本公司";
                this.BindData();

            }
        }
        private void BindAccountID()
        {
            var bll = mk.l.Sales_Account.ToList();
            var ds = bll.Where(h => h.RootDepartmentID.ToString() == this.lblRootDepartmentID.Text);
            this.ddlAccountID.DataSource = ds;
            this.ddlAccountID.DataTextField = "Name";
            this.ddlAccountID.DataValueField = "AccountID";
            this.ddlAccountID.DataBind();
        }
        private void BindData()
        {
            var bllSalesOrderHeader = mk.l.Sales_SalesOrderHeader.ToList();

            Sales_SalesOrderHeader mSalesOrderHeader = bllSalesOrderHeader.Where(h => h.SalesOrderID == (int.Parse(this.lblSalesOrderID.Text))).FirstOrDefault();


            if (mSalesOrderHeader != null)
            {
                //判断是否是本店的订单
                if (int.Parse(this.lblRootDepartmentID.Text) == mSalesOrderHeader.RootDepartmentID)
                {
                    //先判断一下是否已经提交 没提交的就别管了
                    if (mSalesOrderHeader.StatusSubmit != "1")
                    {
                        //判断一下订单是否已完工 完工的就不行了
                        if (mSalesOrderHeader.StatusAll == "1")
                        {
                            if (mSalesOrderHeader.StatusPayment != "3")
                            {
                                if (mSalesOrderHeader.TotalDue > 0)
                                {
                                    //显示订单数据
                                    this.lblSalesOrderNumber.Text = mSalesOrderHeader.SalesOrderNumber;
                                    //显示付款方信息
                                    var bllCustomer = mk.l.Sales_Customer.ToList();
                                    Sales_Customer mCustomer = bllCustomer.Where(h => h.CustomerID == (mSalesOrderHeader.CustomerID)).FirstOrDefault();
                                    if (mCustomer != null)
                                    {
                                        this.lblInfoFrom.Text = mCustomer.CustomerName + " 电话：" + mCustomer.Phone + " 手机：" + mCustomer.CellPhone;
                                    }
                                    //TODO 此处设置收款金额为客户实付款还是去掉设计师佣金后的实际收入
                                    this.lblTotalDue.Text = mSalesOrderHeader.TotalDue.ToString();
                                    this.lblPrepaidPayment.Text = mSalesOrderHeader.PrepaidPayment.ToString();
                                    this.txtSettlementAmount.Text = (mSalesOrderHeader.TotalDue - mSalesOrderHeader.PrepaidPayment).ToString();
                                }
                                else
                                {
                                    mk.Alert("还未设置客户付款价格！请设置后再进行收款操作");
                                }
                            }
                            else
                            {
                                mk.Alert("此订单已经收款完毕！");
                            }
                        }
                        else
                        {
                            mk.Alert("此订单已经完工！");
                        }
                    }
                    else
                    {
                        mk.Alert("此订单尚未提交！");
                    }
                }
                else
                {
                    mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
                mk.Alert("参数错误！");
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                //实例化销售订单业务逻辑类
                var bllSalesOrderHeader =
                   mk.l.Sales_SalesOrderHeader.ToList();
                //使用业务逻辑类获取特定销售定单编号的订单实体
                Sales_SalesOrderHeader mSalesOrderHeader =
             bllSalesOrderHeader.Where(h => h.SalesOrderID == int.Parse(this.lblSalesOrderID.Text)).FirstOrDefault();
                if (mSalesOrderHeader != null)
                {
                    //先判断一下是否已经提交 如果未提交不能确认收款
                    if (mSalesOrderHeader.StatusSubmit != "1")
                    {
                        //判断一下订单是否已完工 如果订单完成不能进行收款 
                        if (mSalesOrderHeader.StatusAll == "1")
                        {
                            if (mSalesOrderHeader.StatusPayment != "3")
                            {
                                //实例化结算业务逻辑类
                                var bll =
                                     mk.l.Sales_SettlementDetail.ToList();
                                //实例化结算对象实例
                                Sales_SettlementDetail m =
                                     new Sales_SettlementDetail();
                                //得到用户在下拉列表框中选择的账户
                                m.AccountID = int.Parse(this.ddlAccountID.SelectedValue);
                                //获取收款日期
                                m.DateReckoning = Convert.ToDateTime(this.txtDateReckoning.Date);
                                m.Flag = "2";
                                m.InfoFrom = this.lblInfoFrom.Text;
                                m.InfoTo = this.lblInfoTo.Text;
                                m.Manager = this.lblManagerUserName.Text;
                                m.ModifiedDate = System.DateTime.Now;
                                //备注信息
                                m.Notes = mk.InputText(this.txtNotes.Text, 200);
                                m.PurchaseOrderID = 0;
                                m.RootDepartmentID = int.Parse(this.lblRootDepartmentID.Text);
                                m.SalesOrderID = int.Parse(this.lblSalesOrderID.Text);
                                //金额设置为正值
                                m.SettlementAmount = decimal.Parse(this.txtSettlementAmount.Text);
                                //购买原材料付款的类别ID为1，客户收款ID为2
                                m.TypeID = 2;
                                try
                                {
                               mk.l.Sales_SettlementDetail.InsertOnSubmit(m);        //添加一条新的收款信息
                                    //更新账户的信息
                                    var bllAccount =
                                         mk.l.Sales_Account.ToList();
                                    Sales_Account mAccount =
                                           bllAccount.Where(h => h.AccountID == int.Parse(this.ddlAccountID.SelectedValue)).FirstOrDefault();
                                    //汇总余额信息
                                    mAccount.Balance += decimal.Parse(this.txtSettlementAmount.Text);
                                    mk.l.SubmitChanges();
                                    //更改订单的付款状态付款时间
                                    var bllHeader =
                                         mk.l.Sales_SalesOrderHeader.ToList();
                                    Sales_SalesOrderHeader mHeader =
                                 bllHeader.Where(h => h.SalesOrderID == int.Parse(this.lblSalesOrderID.Text)).FirstOrDefault();
                                    //如果选中了已付全款的选项 则设置付款状态为3
                                    if (this.chkIsPaymentDone.Checked == true)
                                    {
                                        mHeader.StatusPayment = "3";
                                    }
                                    else
                                    {
                                        mHeader.StatusPayment = "2";
                                    }
                                    //设置订单的已付款和未付款
                                    mHeader.PrepaidPayment +=
                                        decimal.Parse(this.txtSettlementAmount.Text);
                                    mHeader.ResidualPayment =
                                        mHeader.TotalDue - mHeader.PrepaidPayment;
                                    //如果余款小于等于0，说明已经付完全款 设置付款状态
                                    if (mHeader.ResidualPayment <= 0)
                                    {
                                        mHeader.StatusPayment = "3";
                                    }
                                    mHeader.ModifiedDate = System.DateTime.Now;
                                    mk.l.SubmitChanges();
                                    //提交事务
                                    //  ContextUtil.SetComplete();
                                    mk.Alert("收款成功！");
                                }
                                catch (Exception ex)
                                {
                                    //撤销事务
                                    //  ContextUtil.SetAbort();
                                    mk.Alert
                                         ("收款失败！错误信息：" + ex.Message);
                                }
                            }
                            else
                            {
                                mk.Alert
                                     ("此订单已经收款完毕！");
                            }
                        }
                        else
                        {
                            mk.Alert("此订单已经完工！");
                        }
                    }
                    else
                    {
                        mk.Alert("此订单尚未提交！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }
            }
        }
        protected void ddlAccountID_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ShowCurrentBalance();
        }

        /// <summary>
        /// Shows the current balance.
        /// </summary>
        private void ShowCurrentBalance()
        {
            if (this.ddlAccountID.SelectedValue != "")
            {
                var bll = mk.l.Sales_Account.ToList();
                Sales_Account m = bll.Where(h => h.AccountID == int.Parse(this.ddlAccountID.SelectedValue)).FirstOrDefault();
                this.lblCurrentBalance.Text = m.Balance.ToString();
            }
        }

        /// <summary>
        /// Handles the ServerValidate event of the CustomValidator1 control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            var bll = mk.l.Sales_SalesOrderHeader.ToList();
            Sales_SalesOrderHeader m = bll.Where(h => h.SalesOrderID == int.Parse(this.lblSalesOrderID.Text)).FirstOrDefault();
            if (m.StatusPayment == "3")
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
    }
}